import requests
import re
import json
import os
from django.conf import settings
import hashlib

PAGE_URL = "https://www.bilibili.com/video/"
HEADERS = {
    "referer": "https://www.bilibili.com",
    "sec-ch-ua": '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
    "sec-ch-ua-mobile": '?0',
    "sec-fetch-dest": 'empty',
    'sec-fetch-mode': 'cors',
    "sec-fetch-site": "same-site",
    "user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
}
MUSIC_FILE_DIR = settings.MUSIC_FILE_DIR
MUSIC_IMAGE_DIR = settings.MUSIC_IMAGE_DIR

def pick_music_from_bilibili(bv):
    page_html = requests.get(url=PAGE_URL + bv, headers=HEADERS).text

    music_name_pattern = re.compile(r'<meta data-vue-meta="true" itemprop="name" name="title" content="(.*?)">')
    music_up_pattern = re.compile(r'<meta data-vue-meta="true" itemprop="author" name="author" content="(.*?)">')
    music_release_time_pattern = re.compile(r'<meta data-vue-meta="true" itemprop="uploadDate" content="(.*?)">')
    music_image_pattern = re.compile(r'<meta data-vue-meta="true" itemprop="image" content="(.*?)">')
    music_file_pattern = re.compile(r'<script>window.__playinfo__=(.*?)</script>')
    
    music_name = music_name_pattern.findall(page_html)
    music_up = music_up_pattern.findall(page_html)
    music_release_time = music_release_time_pattern.findall(page_html)
    music_image_url = music_image_pattern.findall(page_html)
    music_file_result = music_file_pattern.findall(page_html)

    if len(music_name) == 0 or len(music_up) == 0 or len(music_release_time) == 0 or len(music_image_url) == 0 or len(music_file_result) == 0:
        print(f'len(music_name)={len(music_name)}')
        print(f'len(music_up)={len(music_up)}')
        print(f'len(music_release_time)={len(music_release_time)}')
        print(f'len(music_image_url)={len(music_image_url)}')
        print(f'len(music_file_result)={len(music_file_result)}')
        raise Exception("search error!")
    
    music_name = music_name[0][:-26]
    music_up = music_up[0]
    music_release_time = music_release_time[0]
    music_image_url = music_image_url[0]
    music_file_result = json.loads(music_file_result[0])
    music_file_url = music_file_result['data']['dash']['audio'][0]['base_url']

    print(f'music_name: {music_name}')
    print(f'music_up: {music_up}')
    print(f'music_bv: {bv}')
    print(f'music_release_time: {music_release_time}')
    print(f'music_image_url: {music_image_url}')
    print(f'music_file_url: {music_file_url}')

    music_hash_name = hashlib.md5()
    music_hash_name.update(music_name.encode('utf8'))
    music_hash_name = music_hash_name.hexdigest()

    music_image = requests.get(url=music_image_url, headers=HEADERS).content
    with open(os.path.join(MUSIC_IMAGE_DIR, music_hash_name+"."+music_image_url.split(".")[-1]), "wb") as f:
        f.write(music_image)

    music_file = requests.get(url=music_file_url, headers=HEADERS).content
    with open(os.path.join(MUSIC_FILE_DIR, music_hash_name+".mp3"), "wb") as f:
        f.write(music_file)

    return music_name, music_up, bv, music_release_time, music_hash_name+".mp3", music_hash_name+"."+music_image_url.split(".")[-1]

if __name__ == "__main__":
    MUSIC_FILE_DIR = "D:\\Project_Manager\\music_bilibili"
    MUSIC_IMAGE_DIR = "D:\\Project_Manager\\music_bilibili"
    bv = 'BV1h7411N7Uf'

    try:
        result = pick_music_from_bilibili(bv)
        print(f'result={result}')
    except Exception as e:
        print(e)
